package com.ojoin.trade.common.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ojoin.trade.common.web.service.impl.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ojoin.trade.common.web.domain.BaseEntity;
import com.ojoin.trade.common.web.domain.Office;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Role;
import com.ojoin.trade.common.web.domain.User;
import com.ojoin.trade.common.web.service.SysManageService;

@Controller
@RequestMapping(value = "sys/user")
public class UserController extends SimpleBaseController {

	@Autowired
	private SysManageService systemService;

	@ModelAttribute("user")
	public User get(@RequestParam(required = false) Integer id) {
		if (null != id) {
			return  systemService.get(id);
		} else {
			return  new User();
		}
	}

	@RequiresPermissions("sys:user:view")
	@ResponseBody
	@RequestMapping(value =  "list")
	public Result list(User user, Pageable page) {
		return new Result(Result.Status.OK, systemService.findUser(user, page));
	}

	@RequiresPermissions("sys:user:view")
	@ResponseBody
	@RequestMapping(value = "form")
	public Result form(User user) {
		Map ret = new HashMap();
		if (user.getCompany() == null || user.getCompany().getId() == null) {
			user.setCompany(systemService.getUser().getCompany());
		}
		if (user.getOffice() == null || user.getOffice().getId() == null) {
			user.setOffice(systemService.getUser().getOffice());
		}
		ret.put("user", user);
		ret.put("allRoles", systemService.getRoleList());
		return new Result(Result.Status.OK, ret);
	}

	@RequiresPermissions("sys:user:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public Result save(User user, HttpServletRequest request) {
		String ret;
		user.setCompany(new Office(Integer.valueOf(request
				.getParameter("company.id"))));
		user.setOffice(new Office(Integer.valueOf(request
				.getParameter("office.id"))));
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(user.getNewPassword())) {
			user.setPassword(UserUtils.entryptPassword(user.getNewPassword()));
		}

		if (!"true".equals(checkLoginName(user.getOldLoginName(),
				user.getLoginName()))) {
			ret = "保存用户'" + user.getLoginName() + "'失败，登录名已存在";
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<String> roleIdList = user.getRoleIdList();
		for (Role r : systemService.getRoleList()) {
			if (roleIdList.contains(String.valueOf(r.getId()))) {
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(systemService.getUser().getLoginName())||(null!=user.getId()&&user.getId().intValue()==(systemService.getUser().getId().intValue()))) {
			systemService.clearCache();
		}
		ret = "保存用户'" + user.getLoginName() + "'成功";
		return new Result(Result.Status.OK, ret);
	}

	@RequiresPermissions("sys:user:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public Result delete(User user) {
		String ret;
		if (systemService.getUser().getId().equals(user.getId())) {
			ret = "删除用户失败, 不允许删除当前用户";
		} else if (User.isAdmin(user.getId())) {
			ret = "删除用户失败, 不允许删除超级管理员用户";
		} else {
			user.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
			systemService.deleteUser(user);
			ret = "删除用户成功";
		}
		return new Result(Result.Status.OK, ret);
	}

	/**
	 * 验证登录名是否有效
	 * 
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@ResponseBody
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName != null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName != null
				&& systemService.getByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 用户信息显示及保存
	 * 
	 * @param user
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "info")
	public Result info(User user, HttpServletResponse response) {
		User currentUser = systemService.getUser();
		if (StringUtils.isNotBlank(user.getName())) {
			currentUser.setEmail(user.getEmail());
			currentUser.setPhone(user.getPhone());
			currentUser.setMobile(user.getMobile());
			currentUser.setRemarks(user.getRemarks());
			currentUser.setPhoto(user.getPhoto());
			systemService.updateUserInfo(currentUser);
		}
		return new Result(Result.Status.OK, "保存用户信息成功");
	}

	/**
	 * 返回用户信息
	 * 
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "infoData")
	public Result infoData() {
		return new Result(Result.Status.OK, systemService.getUser());
	}

	/**
	 * 修改个人用户密码
	 * 
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "modifyPwd")
	public Result modifyPwd(String oldPassword, String newPassword) {
		User user = systemService.getUser();
		if (StringUtils.isNotBlank(oldPassword)
				&& StringUtils.isNotBlank(newPassword)) {
			
			if (UserUtils.validatePassword(oldPassword,user.getPassword())) {
				systemService.updatePasswordById(user.getId(),
						user.getLoginName(), newPassword);
				return new Result(Result.Status.OK, user);
			} else {
				return new Result(Result.Status.ERROR, "修改密码失败，旧密码错误");
			}
		}
		return new Result(Result.Status.ERROR, "修改密码失败，密码空");
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public Result treeData(@RequestParam(required = false) Integer officeId) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<User> list = systemService.findUserByOfficeId(officeId);
		for (int i = 0; i < list.size(); i++) {
			User e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", "u_" + e.getId());
			map.put("pId", officeId);
			map.put("name", StringUtils.replace(e.getName(), " ", ""));
			mapList.add(map);
		}
		return new Result(Result.Status.OK, mapList);
	}

}
